import threading
import urllib2
import zipfile
import datetime

from cStringIO import StringIO

from django.conf import settings

class ProcessDownloadQueue(threading.Thread):
    def __init__(self, instance):
        self.instance = instance
        threading.Thread.__init__(self)

    def run(self):
        storage_module = settings.ARCADE_STORAGE_MODULE
        try:
            mod = __import__(storage_module, {}, {}, [''])
        except ImportError, e:
            raise exceptions.ImproperlyConfigured, 'Error importing storage handler %s: "%s"' % (storage_module, e)
        try:
            store_func = getattr(mod, 'store')
        except AttributeError:
            raise exceptions.ImproperlyConfigured, 'Storage module "%s" does not define a "store" function' % (storage_module,)
        
        try:
            print "grabbing zip file..."
            zip_file = urllib2.urlopen("http://cdn.mochiads.com/c/g/%s.zip" % (self.instance.slug,))
            try:
                zip_data = StringIO(zip_file.read())
                store_func(zip_data, self.instance.slug)
                self.instance.downloaded = True
                self.instance.download = False
                self.instance.site_added_date = datetime.datetime.now()
            except Exception, e:
                raise
                self.instance.download = False
        except urllib2.HTTPError, e:
            raise
            self.instance.download = False
        self.instance.save()
        